package com.tiancheng.trade.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.commom.core.data.PageInfo;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.enums.PaySceneEnum;
import com.tiancheng.trade.commom.core.enums.PaymentWayEnum;
import com.tiancheng.trade.commom.core.exception.BusinessException;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.bo.OrderQueryBO;
import com.tiancheng.trade.order.bo.cmq.RefundResultMsgBO;
import com.tiancheng.trade.order.enums.*;
import com.tiancheng.trade.order.feign.OrderSubSystemService;
import com.tiancheng.trade.order.feign.dto.orderSubSystem.RefundCreateDTO;
import com.tiancheng.trade.order.feign.dto.orderSubSystem.RefundSubmitDTO;
import com.tiancheng.trade.order.mapper.OrderMapper;
import com.tiancheng.trade.order.mapper.RefundOrdersDetailMapper;
import com.tiancheng.trade.order.model.Order;
import com.tiancheng.trade.order.model.RefundOrdersDetail;
import com.tiancheng.trade.order.service.OrderParallelService;
import com.tiancheng.trade.order.service.OrderService;
import com.tiancheng.trade.order.service.SubOrderStatusService;
import com.tiancheng.trade.order.util.EnumUtil;
import com.tiancheng.trade.order.util.ObjectConvertUtil;
import com.tiancheng.trade.order.util.OrderParallelUtil;
import com.tiancheng.trade.order.mq.MessageProducer;
import com.tiancheng.trade.order.vo.api.CreditOrderVo;
import com.tiancheng.trade.order.vo.api.RefundAuditVO;
import com.tiancheng.trade.order.vo.api.RefundVO;
import com.tiancheng.trade.order.vo.api.res.RefundCreateResVO;
import com.tiancheng.trade.order.vo.app.CashierVO;
import com.tiancheng.trade.order.vo.app.res.OrderPrePayResVO;
import com.tiancheng.trade.order.vo.open.order.OpenCashierResVO;
import com.tiancheng.trade.order.vo.open.order.OpenOrderPayVO;
import com.tiancheng.trade.order.vo.parallel.*;
import com.tiancheng.trade.order.vo.parallel.res.*;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 新老系统并行数据处理Service接口实现
 *
 * @author kellen
 * @date 2024/6/5
 */
@Service
public class OrderParallelServiceImpl implements OrderParallelService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RefundOrdersDetailMapper refundOrdersDetailMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderSubSystemService orderSubSystemService;
    @Resource
    private MessageProducer messageProducer;
    @Resource
    private SubOrderStatusService subOrderStatusService;

    @Override
    public PageInfo<OrderQueryResVO> findByUser(OrderQueryVO orderQueryVO) {
        final OrderQueryBO orderQueryBO = new OrderQueryBO();
        orderQueryBO.setUid(orderQueryVO.getUid());
        if(!StringUtils.isEmpty(orderQueryVO.getOrderSource())){
            orderQueryBO.setOrderSource(Arrays.asList(orderQueryVO.getOrderSource().split(",")));
        }
        orderQueryBO.setStartTime(orderQueryVO.getStartTime());
        orderQueryBO.setEndTime(orderQueryVO.getEndTime());

        orderQueryBO.setPage(orderQueryVO.getPage());
        orderQueryBO.setSize(orderQueryVO.getSize());
        orderQueryBO.setPayStatus(orderQueryVO.getPayStatus());
        if(!StringUtils.isEmpty(orderQueryVO.getOrderStatus())){
            orderQueryBO.setOrderStatus(Arrays.asList(orderQueryVO.getOrderStatus().split(",")));
        }
        orderQueryBO.setSystemSources(orderQueryVO.getSystemSources());
        final long count = orderMapper.findByUidCount(orderQueryBO);
        List<Order> orders = new ArrayList<>();
        if(count>0){
            orders=orderMapper.findByUid(orderQueryBO);
        }

        List<OrderQueryResVO> resOrders = new ArrayList<>();
        for (Order order : orders) {
            OrderSourceEnum orderSourceEnum = EnumUtil.getEnumByCode(OrderSourceEnum.class, order.getOrderSource());
            OrderQueryResVO resVO = new OrderQueryResVO();
            resVO.setOrderId(order.getOrderId());
            resVO.setBatchId(order.getBatchId());
            resVO.setOrderStatus(order.getOrderStatus());
            resVO.setOrderName(order.getOrderName());
            resVO.setOrderSource(orderSourceEnum.name().toLowerCase());
            resVO.setOrderSourceName(orderSourceEnum.getDesc());
            resVO.setOrderStatusName(EnumUtil.getEnumByCode(OrderStatusEnum.class, resVO.getOrderStatus()).getDesc());
            resVO.setPayAmount(new BigDecimal(order.getPayAmount()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
            resVO.setIsRefund(order.getRefundTimes() > 0 ? 1 : 0);
            resVO.setCreateTime(order.getCreatedDt());
            resVO.setBatchDesc(OrderParallelUtil.getBatchDesc(orderSourceEnum, order.getTradeInfo()));
            resVO.setIsCanMergePay(false);        //新旧系统并行时，暂时不支持合单支付
            resVO.setTradeInfo(order.getTradeInfo());
            resOrders.add(resVO);
        }
        return new PageInfo<>(resOrders, new PageInfo.Pagination(orderQueryVO.getPage(), orderQueryVO.getSize(), count));
    }

    @Override
    public PageInfo<OrderQueryResNewVO> findByUserNew(OrderQueryVO orderQueryVO) {
        QueryWrapper<Order> conditions = new QueryWrapper<>();
        conditions.eq("uid", orderQueryVO.getUid());
        if (!StringUtils.isEmpty(orderQueryVO.getOrderSource())) {
            conditions.in("order_source", orderQueryVO.getOrderSource().split(","));
        }
        if (!StringUtils.isEmpty(orderQueryVO.getPayStatus())) {
            conditions.eq("pay_status", orderQueryVO.getPayStatus());
        }
        if (!StringUtils.isEmpty(orderQueryVO.getOrderStatus())) {
            conditions.in("order_status", orderQueryVO.getOrderStatus().split(","));
        }
        if (orderQueryVO.getStartTime() != null) {
            conditions.gt("created_dt", orderQueryVO.getStartTime());
        }
        if (orderQueryVO.getEndTime() != null) {
            conditions.lt("created_dt", orderQueryVO.getEndTime());
        }

        // 不显示续单、尾单
        conditions.eq("original_order_id", "0");
        conditions.orderByDesc("created_dt");

        PageInfo<Order> orders = orderMapper.find(conditions, orderQueryVO.getPage(), orderQueryVO.getSize());

        List<OrderQueryResNewVO> resOrders = new ArrayList<>();
        for (Order order : orders.getList()) {
            OrderSourceEnum orderSourceEnum = EnumUtil.getEnumByCode(OrderSourceEnum.class, order.getOrderSource());
            OrderQueryResNewVO resVO = new OrderQueryResNewVO();
            resVO.setOrderId(order.getOrderId());
            resVO.setOrderStatus(order.getOrderStatus());
            resVO.setOrderName(order.getOrderName());
            resVO.setOrderSource(order.getOrderSource());
            resVO.setOrderSourceName(orderSourceEnum.getDesc());
            resVO.setOrderStatusName(EnumUtil.getEnumByCode(OrderStatusEnum.class, resVO.getOrderStatus()).getDesc());
            resVO.setPayAmount(new BigDecimal(order.getPayAmount()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
            resVO.setIsRefund(order.getRefundTimes() > 0 ? 1 : 0);
            resVO.setCreateTime(order.getCreatedDt());
            resVO.setBatchDesc(OrderParallelUtil.getBatchDesc(orderSourceEnum, order.getTradeInfo()));
            resVO.setIsCanMergePay(false);        //新旧系统并行时，暂时不支持合单支付
            resVO.setTradeInfo(order.getTradeInfo());
            resOrders.add(resVO);
        }

        return new PageInfo<>(resOrders, new PageInfo.Pagination(orderQueryVO.getPage(), orderQueryVO.getSize(), orders.getPagination().getTotal()));
    }

    @Override
    public PageInfo<RefundQueryResVO> findRefundByUser(RefundQueryVO refundQueryVO) {
        QueryWrapper<RefundOrdersDetail> conditions = new QueryWrapper<>();
        conditions.eq("uid", refundQueryVO.getUid());
        if (!StringUtils.isEmpty(refundQueryVO.getOrderSource())) {
            conditions.in("order_source", refundQueryVO.getOrderSource().split(","));

        }
        if (refundQueryVO.getStartTime() != null) {
            conditions.gt("created_dt", refundQueryVO.getStartTime());
        }
        if (refundQueryVO.getEndTime() != null) {
            conditions.lt("created_dt", refundQueryVO.getEndTime());
        }
        if (!StringUtils.isEmpty(refundQueryVO.getRefundStatus())) {
            conditions.eq("refund_status", refundQueryVO.getRefundStatus());
        }
        conditions.orderByDesc("created_dt");

        PageInfo<RefundOrdersDetail> refunds = refundOrdersDetailMapper.find(conditions, refundQueryVO.getPage(), refundQueryVO.getSize());
        List<Order> orders = new ArrayList<Order>();
        if (!CollectionUtils.isEmpty(refunds.getList())) {
            orders = orderService.findByOrderIds(refunds.getList().stream().map(RefundOrdersDetail::getOrderId).collect(Collectors.toSet()));
        }

        List<RefundQueryResVO> resRefunds = new ArrayList<>();
        for (RefundOrdersDetail refundOrdersDetail : refunds.getList()) {
            Order order = orders.stream().filter(o -> o.getOrderId().equals(refundOrdersDetail.getOrderId())).findFirst().get();
            OrderSourceEnum orderSourceEnum = EnumUtil.getEnumByCode(OrderSourceEnum.class, refundOrdersDetail.getOrderSource());
            RefundQueryResVO resVO = new RefundQueryResVO();
            resVO.setOrderId(refundOrdersDetail.getOrderId());
            resVO.setSubOrderId(refundOrdersDetail.getSubOrderId());
            resVO.setRefundId(refundOrdersDetail.getPaymentId());
            resVO.setMerchantCode(refundOrdersDetail.getMerchantCode());
            resVO.setProductName(refundOrdersDetail.getProductName());
            resVO.setOrderSource(refundOrdersDetail.getOrderSource());
            resVO.setOrderSourceName(orderSourceEnum.name().toLowerCase());
            resVO.setStatus(refundOrdersDetail.getRefundStatus());
            resVO.setStatusName(EnumUtil.getEnumByCode(RefundStatusEnum.class, resVO.getStatus()).getDesc());
            resVO.setRefundAmount(new BigDecimal(refundOrdersDetail.getRefundAmount()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
            resVO.setDescription(refundOrdersDetail.getRefundReason());
            resVO.setCreateTime(refundOrdersDetail.getCreatedDt());
            resVO.setRefundTime(refundOrdersDetail.getRefundTime());
            resVO.setIsPlatformOrder(true);
            resVO.setTradeInfo(order.getTradeInfo());
            resVO.setBatchDesc(OrderParallelUtil.getBatchDesc(orderSourceEnum, order.getTradeInfo()));
            resRefunds.add(resVO);
        }
        return new PageInfo<>(resRefunds, new PageInfo.Pagination(refundQueryVO.getPage(), refundQueryVO.getSize(), refunds.getPagination().getTotal()));
    }

    @Override
    public PageInfo<RefundQueryResNewVO> findRefundByUserNew(RefundQueryVO refundQueryVO) {
        QueryWrapper<RefundOrdersDetail> conditions = new QueryWrapper<>();
        conditions.eq("uid", refundQueryVO.getUid());
        if (!StringUtils.isEmpty(refundQueryVO.getOrderSource())) {
            conditions.in("order_source", refundQueryVO.getOrderSource().split(","));
        }
        if (refundQueryVO.getStartTime() != null) {
            conditions.gt("created_dt", refundQueryVO.getStartTime());
        }
        if (refundQueryVO.getEndTime() != null) {
            conditions.lt("created_dt", refundQueryVO.getEndTime());
        }
        if (!StringUtils.isEmpty(refundQueryVO.getRefundStatus())) {
            conditions.eq("refund_status", refundQueryVO.getRefundStatus());
        }
        /*if(CollectionUtils.isEmpty(refundQueryVO.getSystemSources())){
            // 不传系统来源时，默认只查平台（YOUYUNNAN）的
            conditions.and(orderQueryWrapper -> orderQueryWrapper.isNull("system_source").or().eq("system_source", SystemSourceEnum.YOUYUNNAN.getCode()));
        }else{
            // 否则根据传入的系统来源来限制显示的订单
            conditions.in("system_source",refundQueryVO.getSystemSources());
        }*/
        conditions.orderByDesc("created_dt");

        PageInfo<RefundOrdersDetail> refunds = refundOrdersDetailMapper.find(conditions, refundQueryVO.getPage(), refundQueryVO.getSize());
        List<Order> orders = new ArrayList<Order>();
        if (!CollectionUtils.isEmpty(refunds.getList())) {
            orders = orderService.findByOrderIds(refunds.getList().stream().map(RefundOrdersDetail::getOrderId).collect(Collectors.toSet()));
        }

        List<RefundQueryResNewVO> resRefunds = new ArrayList<>();
        for (RefundOrdersDetail refundOrdersDetail : refunds.getList()) {
            Order order = orders.stream().filter(o -> o.getOrderId().equals(refundOrdersDetail.getOrderId())).findFirst().get();
            OrderSourceEnum orderSourceEnum = EnumUtil.getEnumByCode(OrderSourceEnum.class, refundOrdersDetail.getOrderSource());

            RefundQueryResNewVO resVO = new RefundQueryResNewVO();
            resVO.setOrderId(refundOrdersDetail.getOrderId());
            resVO.setSubOrderId(refundOrdersDetail.getSubOrderId());
            resVO.setRefundId(refundOrdersDetail.getPaymentId());
            resVO.setMerchantCode(refundOrdersDetail.getMerchantCode());
            resVO.setProductName(refundOrdersDetail.getProductName());
            resVO.setOrderSource(refundOrdersDetail.getOrderSource());
            resVO.setOrderSourceName(orderSourceEnum.getDesc());
            resVO.setStatus(refundOrdersDetail.getRefundStatus());
            resVO.setStatusName(EnumUtil.getEnumByCode(RefundStatusEnum.class, resVO.getStatus()).getDesc());
            resVO.setRefundAmount(new BigDecimal(refundOrdersDetail.getRefundAmount()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP));
            resVO.setDescription(refundOrdersDetail.getRefundReason());
            resVO.setCreateTime(refundOrdersDetail.getCreatedDt());
            resVO.setRefundTime(refundOrdersDetail.getRefundTime());
            resVO.setIsPlatformOrder(true);
            resVO.setTradeInfo(order.getTradeInfo());
            resVO.setBatchDesc(OrderParallelUtil.getBatchDesc(orderSourceEnum, order.getTradeInfo()));
            resRefunds.add(resVO);
        }
        return new PageInfo<>(resRefunds, new PageInfo.Pagination(refundQueryVO.getPage(), refundQueryVO.getSize(), refunds.getPagination().getTotal()));
    }

    @Override
    public CashierParallelResVO initCashier(CashierParallelVO cashierParallelVO) {
        CashierVO cashierVO = new CashierVO();
        cashierVO.setOrderIds(cashierParallelVO.getOrderIds());
        cashierVO.setAppType(cashierParallelVO.getAppType());
        cashierVO.setAppVersion(cashierParallelVO.getAppVersion());

        OpenCashierResVO cashierResVO = orderService.initCashier(cashierParallelVO.getUid(), cashierVO);
        return ObjectConvertUtil.convert(cashierResVO, CashierParallelResVO.class).get();
    }

    @Override
    public OrderPrePayParallelResVO pay(OrderPayParallelVO orderPayParallelVO) {
        OpenOrderPayVO orderPayVO = ObjectConvertUtil.convert(orderPayParallelVO, OpenOrderPayVO.class).get();
        OrderPrePayResVO orderPrePayResVO = orderService.pay(orderPayParallelVO.getUid(), orderPayVO);

        OrderPrePayParallelResVO resVO = ObjectConvertUtil.convert(orderPrePayResVO, OrderPrePayParallelResVO.class).get();
        if (orderPrePayResVO.getOrders().size() > 1) {
            resVO.setIsMergeOrder(1);
        } else {
            resVO.setType(orderPrePayResVO.getOrders().get(0).getOrderSource());
            resVO.setOrderId(orderPrePayResVO.getOrders().get(0).getOrderId());
        }
        return resVO;
    }

    @Override
    public Map<String, String> getPayStatus(String uid, String orderId) {
        Order order = orderService.get(uid, orderId);
        Map<String, String> res = new HashMap<>();
        res.put("pay_status", order.getPayStatus());
        return res;
    }

    @Override
    public RefundCreateResVO createRefund(RefundVO refundVO) throws BusinessException {
        Map<String, Object> order = orderSubSystemService.getOrderInfo(refundVO.getOrderId());
        BusinessErrorInfoEnum.ORDER_REFUND_NO_DATA.assertNotNull(order);

        RefundVO.SubOrder subOrder = refundVO.getSubOrders().get(0);
        String subOrderId = (order.containsKey("sub_order_id") && !StringUtils.isEmpty(order.get("sub_order_id").toString())) ?
                String.valueOf(order.get("sub_order_id")) : subOrder.getSubOrderId();

        RefundCreateDTO refundCreateDTO = new RefundCreateDTO();
        refundCreateDTO.setOrderId(refundVO.getOrderId());
        refundCreateDTO.setUid(refundVO.getUid());
        refundCreateDTO.setDescription(refundVO.getRefundReason());
        refundCreateDTO.setSubOrderId(subOrderId);
        refundCreateDTO.setMerchantId(String.valueOf(order.get("merchant_id")));
        refundCreateDTO.setGoodsName(String.valueOf(order.get("goods_name")));
        refundCreateDTO.setRefundAmount(subOrder.getRefundAmount() != null ? subOrder.getRefundAmount() : Integer.valueOf(String.valueOf(order.get("pay_amount"))));
        refundCreateDTO.setRefundDetailData("[]");

        Map<String, Object> refundResultMap = orderSubSystemService.createRefund(refundCreateDTO);
        BusinessErrorInfoEnum.ORDER_REFUND_PHP_SYSTEM_ERROR.assertNotNull(refundResultMap);

        RefundCreateResVO refundCreateResVO = new RefundCreateResVO();
        refundCreateResVO.setOrderId(refundVO.getOrderId());
        refundCreateResVO.setPaymentId(String.valueOf(refundResultMap.get("refund_id")));
        refundCreateResVO.getSubOrders().add(new RefundCreateResVO.SubOrder(
                subOrderId, refundCreateResVO.getPaymentId(),
                Integer.valueOf(String.valueOf(order.get("pay_amount"))), Integer.valueOf(String.valueOf(order.get("pay_amount"))),
                refundCreateDTO.getRefundAmount()));
        return refundCreateResVO;
    }

    @Override
    public Result submitRefund(RefundAuditVO refundAuditVO) {
        // 审核不通过
        if (!refundAuditVO.isPass()) {
            boolean result = orderSubSystemService.updateRefundStatus(refundAuditVO.getPaymentId(), "refund_fail", "审核不通过");
            if (result) {
                return Result.success();
            } else {
                return Result.fail(BusinessErrorInfoEnum.ORDER_REFUND_PHP_SYSTEM_ERROR.getCode(), "修改状态失败");
            }
        }


        Map<String, Object> order = orderSubSystemService.getOrderInfo(refundAuditVO.getOrderId());
        if (order == null) {
            return Result.fail(BusinessErrorInfoEnum.ORDER_REFUND_NO_DATA.getCode(), "退款失败");
        }

        RefundSubmitDTO refundSubmitDTO = new RefundSubmitDTO();
        refundSubmitDTO.setRefundId(refundAuditVO.getPaymentId());
        refundSubmitDTO.setAmount(refundAuditVO.getSubOrders().get(0).getRefundAmount());
        refundSubmitDTO.setBussSettleAmount(0);
        refundSubmitDTO.setPlatformIncome(refundSubmitDTO.getAmount());

        boolean submitResult = orderSubSystemService.submitRefund(refundSubmitDTO);
        if (!submitResult) {
            return Result.fail(BusinessErrorInfoEnum.ORDER_REFUND_PHP_SYSTEM_ERROR.getCode(), "退款失败");
        }

        // 交易中台的退款成功逻辑，是以回调的方式，需要模拟回调
        RefundResultMsgBO msgBO = new RefundResultMsgBO();
        msgBO.setUid(refundAuditVO.getUid());
        msgBO.setPaymentId(refundAuditVO.getPaymentId());
        msgBO.setRefundTime(LocalDateTime.now());
        msgBO.setStatus("success");
        msgBO.setAmount(refundSubmitDTO.getAmount());
        msgBO.setOrderSource(OrderSourceEnum.valueOf(String.valueOf(order.get("type")).toUpperCase()).code());
        messageProducer.refundResult(msgBO);

        return Result.success();
    }

    @Override
    public void subOrderStatusFlow(String orderId, String[] subOrderId, String bizStatus) {
        Map<String, Object> order = orderSubSystemService.getOrderInfo(orderId);
        BusinessErrorInfoEnum.ORDER_STATUS_FLOW_NO_DATA.assertNotNull(order);

        String subId = (order.containsKey("sub_order_id") && !StringUtils.isEmpty(order.get("sub_order_id").toString())) ?
                String.valueOf(order.get("sub_order_id")) : subOrderId[0];

        OrderSourceEnum orderSourceEnum = OrderSourceEnum.valueOf(String.valueOf(order.get("type")).toUpperCase());
        Map<String, String> statusMap = subOrderStatusService.find(orderSourceEnum.code(), bizStatus);
        BusinessErrorInfoEnum.ORDER_STATUS_FLOW_NO_DATA.assertIsTrue(statusMap != null && statusMap.containsKey(bizStatus));

        // 根据业务侧状态取出订单中心对应的状态值，其中还包括是否核销，格式为SC:1
        String[] values = statusMap.get(bizStatus).split(":");
        String subOrderStatus = values[0];
        String verification = values[1];

        // 先同步老订单中心修改状态
        Map<String, String> oldStatusMap = this.getOrderStatus(orderSourceEnum, bizStatus);
        BusinessErrorInfoEnum.ORDER_STATUS_FLOW_VERIFICATION_ERROR.assertIsTrue(oldStatusMap.size() > 0);
        boolean updateOrderStatusResult = orderSubSystemService.updateOrderStatus(orderId, oldStatusMap.get("status"), oldStatusMap.get("operator"), oldStatusMap.get("desc"));
        BusinessErrorInfoEnum.ORDER_STATUS_FLOW_VERIFICATION_ERROR.assertIsTrue(updateOrderStatusResult);

        // 再调用核销接口，触发核销
        if ("1".equals(verification)) {
            boolean result = orderSubSystemService.verification(orderId, subId);
            BusinessErrorInfoEnum.ORDER_STATUS_FLOW_VERIFICATION_ERROR.assertIsTrue(result);
        }
    }

    @Override
    public String getOrderStr(String orderId) {
        Result result = orderSubSystemService.getOrderStr(orderId);
        BusinessErrorInfoEnum.ORDER_CREDIT_QUERY_OLD_SYSTEM_ERROR.assertIsTrue(result.getRet() == 0);
        return Objects.isNull(result.getData()) ? null : result.getData().toString();
    }

    @Override
    public CreditOrderVo queryCreditOrder(String alipayAuthNo) {
        Result result = orderSubSystemService.queryCreditOrder(alipayAuthNo);
        BusinessErrorInfoEnum.ORDER_CREDIT_QUERY_OLD_SYSTEM_ERROR.assertIsTrue(result.getRet() == 0);
        if (result.getData() != null) {
            return JsonUtil.fromJson(JsonUtil.toJsonString(result.getData()), CreditOrderVo.class);

        }
        return null;
    }

    @Override
    public Result finishCreditOrder(String alipayAuthNo, Integer payAmount, Integer bizComplete, String description) {
        return orderSubSystemService.finishCreditOrder(alipayAuthNo, payAmount, bizComplete, description);
    }

    @Override
    public Result cancelCreditOrder(String alipayAuthNo, String remark) {
        return orderSubSystemService.cancelCreditOrder(alipayAuthNo, remark);
    }

    @Override
    public CreditOrderVo queryConfirmStatus(String orderId) {
        Result result = orderSubSystemService.queryConfirmStatus(orderId);
        if (result.getData() != null) {
            return JsonUtil.fromJson(JsonUtil.toJsonString(result.getData()), CreditOrderVo.class);
        }
        return null;
    }

    @Override
    public Result updateCreditOrderState(Map<String, Object> params) {
        return orderSubSystemService.updateCreditOrderState(params);
    }

    @Override
    public AppleInAppPayResVO appleInAppPay(AppleInAppPayVO appleInAppPayVO) {
        return orderService.appleInAppPay(appleInAppPayVO);
    }

    @Override
    public String deductionPay(OrderDeductionPayParallelVO orderPayVO) {
        // 调用支付
        final OpenOrderPayVO payVO = new OpenOrderPayVO();
        payVO.setOrderId(orderPayVO.getOrderId());
        payVO.setPayWay(PaymentWayEnum.DEDUCTION.getCode());
        payVO.setPayScene(PaySceneEnum.DEDUCTION.getCode());
        orderService.zeroYuanDeductionPay(orderPayVO.getUid(),payVO);
        return null;
    }

    private Map<String, String> getOrderStatus(OrderSourceEnum orderSourceEnum, String bizStatus) {
        Map<String, String> statusMap = new HashMap<>();
        switch (orderSourceEnum) {
            case FLIGHT:
                if ("4".equals(bizStatus)) {
                    statusMap.put("status", "TS");
                    statusMap.put("operator", "draw_ticket");
                    statusMap.put("desc", "出票成功");
                } else if ("5".equals(bizStatus)) {
                    statusMap.put("status", "TF");
                    statusMap.put("operator", "draw_ticket");
                    statusMap.put("desc", "出票失败");
                }
                break;
        }
        return statusMap;
    }
}
